/*
 * (C) Copyright 2014 Kurento (http://kurento.org/)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.one2manycall.service.websocket;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import com.one2manycall.vo.UserSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

/**
 * 对用户进行注册，采用map 结构存储会话
 *
 * @author Boni Garcia (bgarcia@gsyc.es)
 * @author Micael Gallego (micael.gallego@gmail.com)
 * @since 4.3.1
 */
@Component
public class UserRegistry {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserRegistry.class);





    /**
     * 用户名 和sessiong
     */
    private ConcurrentMap<String, UserSession> usersByName = new ConcurrentHashMap<>();

    /**
     *  sessionId 和session
     */
    private ConcurrentMap<String, UserSession> usersBySessionId = new ConcurrentHashMap<>();

    /**
     *  用户注册，实际把用户放入map 表中
     * @param user user
     */
    public void register(UserSession user) {

        LOGGER.info(user.getName() + " : register");
        usersByName.put(user.getName(), user);
        usersBySessionId.put(user.getSession().getId(), user);
    }

    /**
     * 通过用户名称或足球会话session
     * @param name name
     * @return UserSession
     */
    public UserSession getByName(String name) {
        return usersByName.get(name);
    }


    public UserSession getBySession(WebSocketSession session) {
        return usersBySessionId.get(session.getId());
    }

    /**
     * 判断当前用户是否已经存在
     * @param name 用户名称
     * @return
     */
    public boolean exists(String name) {
        return usersByName.keySet().contains(name);
    }

    /**
     *  移除一个session ,先判断是否存在，然后移除
     * @param session session
     * @return  UserSession
     */
    public UserSession removeBySession(WebSocketSession session) {
        final UserSession user = getBySession(session);
        if (user != null) {
            usersByName.remove(user.getName());
            usersBySessionId.remove(session.getId());
        }
        return user;
    }

    /**
     *  获取当前直播间的所有用户
     * @return  UserSession
     */
    public  ConcurrentMap<String, UserSession> getAll() {


        return usersByName;

    }


}
